// 心血管设备数据类型
export type CardiovascularMeasurement = {
    value: {
        ecg?: number;           // 心电值
        heartRate?: number;     // 心率
        spo2?: number;          // 血氧饱和度
        systolic?: number;      // 收缩压
        diastolic?: number;     // 舒张压
        cuffPressure?: number;  // 实时袖带压力
        hrv?: number | null;
        st?: number | null;
        stressIndex?: number;   // 压力指数
        heartAttackIndex?: number; // 心康指数
        progress: number | null;
    };
    unit: {
        ecg?: string;
        heartRate?: string;
        spo2?: string;
        systolic?: string;
        diastolic?: string;
        cuffPressure?: string;
        hrv?: string;
        st: "mv";
        stressIndex: "%";       // 压力指数单位
        heartAttackIndex: "%";   // 心康指数单位
        progress: "";
    };
    rawData: string;
    timestamp: string;
    // 导联状态信息
    leadStatus?: {
        RA: boolean; // RA导联脱落信息 (true:脱落)
        LA: boolean; // LA导联脱落信息 (true:脱落)
        LL: boolean; // LL导联脱落信息 (true:脱落)
    };
};

class CardiovascularParser {
    // BLE服务和特征UUID
    static readonly SERVICE_UUID: string = '00001228-0000-1000-8000-00805f9b34fb';
    // 血压测量,开始测量发送55,然后会这个主题会持续发送实时值,最后一条数据会上报收缩舒张压
    static readonly BLOOD_PRESSURE_CHARACTERISTIC: string = '00002a35-0000-1000-8000-00805f9b34fb';
    static readonly HEART_RATE_CHARACTERISTIC: string = '00002a3f-0000-1000-8000-00805f9b34fb';
    static readonly ECG_CHARACTERISTIC: string = '00002a37-0000-1000-8000-00805f9b34fb';
    static readonly COMMAND_CHARACTERISTIC: string = '00002a35-0000-1000-8000-00805f9b34fb';

    // 用于存储收集到的 st 值
    private static stValues: number[] = [];
    // 用于存储当前的进度值，保持进度的连续性
    private static currentProgress: number | null = null;

    // 为了兼容DeviceTemplate，添加通用特征定义
    static readonly DATA_CHARACTERISTIC: string = '00002a35-0000-1000-8000-00805f9b34fb';

    // 命令定义
    static readonly START_BLOOD_PRESSURE_COMMAND: string = '55'; // 开始血压测量
    static readonly STOP_BLOOD_PRESSURE_COMMAND: string = '56'; // 停止血压测量
    static readonly START_HRV_COMMAND: string = '45'; // 开始心电测量

    static readonly START_COMMAND: string = '55'; // 开始命令
    static readonly STOP_COMMAND: string = '56'; // 通用停止命令

    // 函数无作用
    static parseData(hexString: string): CardiovascularMeasurement | null {
        if (!hexString || hexString.length < 4) {
            return null;
        }

        try {
            // 转换为字节数组
            const bytes = new Uint8Array(hexString.length / 2);
            for (let i = 0; i < hexString.length; i += 2) {
                bytes[i / 2] = parseInt(hexString.substr(i, 2), 16);
            }

            const measurement: CardiovascularMeasurement = {
                value: {
                    // 使用静态变量中存储的进度值，而不是每次都初始化为null
                    progress: this.currentProgress
                },
                unit: {
                    st: "mv",
                    progress: ""
                },
                rawData: hexString,
                timestamp: new Date().toISOString()
            };

            // 根据数据帧头判断数据类型（旧协议：单特征上报）
            const frameHeader = bytes[0];

            if (frameHeader === 0x5A) {
                // 心电数据帧 (假设格式)
                if (bytes.length >= 4) {
                    const ecgValue = (bytes[2] << 8) | bytes[1]; // 小端序
                    measurement.value.ecg = ecgValue;
                    measurement.unit.ecg = 'mV';
                }
            } else if (frameHeader === 0xAA) {
                // 血氧和心率数据帧
                if (bytes.length >= 6) {
                    const heartRate = bytes[2];
                    const spo2 = bytes[3];

                    if (heartRate > 0 && heartRate <= 200) {
                        measurement.value.heartRate = heartRate;
                        measurement.unit.heartRate = 'BPM';
                    }

                    if (spo2 > 0 && spo2 <= 100) {
                        measurement.value.spo2 = spo2;
                        measurement.unit.spo2 = '%';
                    }
                }
            } else if (frameHeader === 0xBB) {
                // 血压数据帧
                if (bytes.length >= 4) {
                    const systolic = bytes[1];
                    const diastolic = bytes[2];

                    if (systolic > 0 && diastolic > 0) {
                        measurement.value.systolic = systolic;
                        measurement.value.diastolic = diastolic;
                        measurement.unit.systolic = 'mmHg';
                        measurement.unit.diastolic = 'mmHg';
                    }
                }
            }

            // 如果没有解析到任何有效数据，返回null
            if (Object.keys(measurement.value).length === 0) {
                return null;
            }

            return measurement;

        } catch (error) {
            console.error('心血管数据解析错误:', error);
            return null;
        }
    }

    // 新增：带元信息解析（多特征订阅场景）
    static parseDataWithMeta(hexString: string, meta: {
        characteristicUUID: string
    } | undefined): CardiovascularMeasurement | null {
        if (!hexString || hexString.length < 2) return null;

        // 容错：meta 或 characteristicUUID 缺失时，回退旧解析
        if (!meta || !meta.characteristicUUID) {
            return this.parseData(hexString);
        }

        const normalized = meta.characteristicUUID;

        try {
            const bytes = new Uint8Array(hexString.length / 2);
            for (let i = 0; i < hexString.length; i += 2) {
                bytes[i / 2] = parseInt(hexString.substr(i, 2), 16);
            }
            const measurement: CardiovascularMeasurement = {
                value: {
                    // 使用静态变量中存储的进度值，而不是每次都初始化为null
                    progress: this.currentProgress
                },
                unit: {
                    st: "mv",
                    progress: ""
                },
                rawData: hexString,
                timestamp: new Date().toISOString()
            };

            // 分通道解析（互斥分支，避免回退覆盖）
            switch (normalized) {
                case CardiovascularParser.BLOOD_PRESSURE_CHARACTERISTIC: {
                    // 新协议：
                    // 实时袖带压力: 2字节 [0]=0x05, [1]=压力(0~255)
                    // 最终结果: 4字节 [0]=0x10, [1]=有效性(0x00有效/0x01无效), [2]=收缩压, [3]=舒张压
                    const frameType = bytes[0];
                    switch (frameType) {
                        case 0x05:
                            if (bytes.length >= 2) {
                                const pressure = bytes[1];
                                if (pressure > 0) {
                                    measurement.value.cuffPressure = pressure;
                                    measurement.unit.cuffPressure = 'mmHg';
                                }
                            }
                            break;
                        case 0x10:
                            if (bytes.length >= 4) {
                                const validity = bytes[1];
                                const systolic = bytes[2];
                                const diastolic = bytes[3];
                                if (validity === 0x00) {
                                    if (systolic > 0) {
                                        measurement.value.systolic = systolic;
                                        measurement.unit.systolic = 'mmHg';
                                    }
                                    if (diastolic > 0) {
                                        measurement.value.diastolic = diastolic;
                                        measurement.unit.diastolic = 'mmHg';
                                    }
                                }
                            }
                            break;
                    }
                    break;
                }
                case CardiovascularParser.HEART_RATE_CHARACTERISTIC: {
                    // 心率/血氧
                    if (bytes.length >= 4) {
                        const heartRate = bytes[2];
                        const spo2 = bytes[3];
                        if (heartRate > 0 && heartRate <= 220) {
                            measurement.value.heartRate = heartRate;
                            measurement.unit.heartRate = 'BPM';
                        }
                        if (spo2 > 0 && spo2 <= 100) {
                            measurement.value.spo2 = spo2;
                            measurement.unit.spo2 = '%';
                        }
                    }
                    break;
                }
                case CardiovascularParser.ECG_CHARACTERISTIC: {
                    const frameType = bytes[0];
                    switch (frameType) {
                        case 0x05:
                            const highByte = bytes[1];    // ST 值的高字节
                            const lowByte = bytes[2];      // ST 值的低字节
                            // 组合为 16 位原始值（大端序）
                            const rawValue = (highByte << 8) | lowByte;
                            // 处理有符号整数（JavaScript 默认无符号）
                            let hrv: number;
                            if (rawValue & 0x8000) {
                                // 如果是负数（最高位为1）
                                hrv = rawValue - 0x10000;  // 转换为有符号负数
                            } else {
                                hrv = rawValue;  // 正数保持不变
                            }

                            // 检查是否为无效值（协议约定 -10000 表示无效）
                            if (hrv === -10000) {
                                measurement.value.hrv = null;  // 标记为无效
                                measurement.value.stressIndex = null;  // 压力指数也标记为无效
                            } else {
                                // 转换为实际 mV 值（原始单位为 0.01 mV）
                                const hrvValue = hrv / 100;
                                measurement.value.hrv = hrvValue;
                                // HRV就是压力指数
                                measurement.value.stressIndex = hrvValue;
                                // measurement.value.st = filteredSt;
                                // 滤波后的ST值也是心康指数
                                measurement.value.heartAttackIndex = this.filterStValues(this.stValues);
                            }
                            console.log(`HRV: ${hrv}`);
                            break;
                        case 0x15:
                            // 组合为 16 位原始值（大端序）
                            const st = (bytes[1] << 8) | bytes[2];
                            if (st > 20000 || st < -20000) {
                                return null;
                            }
                            const stValue = st / 100;
                            // 收集 st 值
                            this.stValues.push(stValue);
                            // 暂时不设置 measurement.value.st，等待滤波后再设置
                            // ST值就是心康指数
                            // measurement.value.heartAttackIndex = stValue;
                            console.log(`ST: ${stValue}`);
                            break;
                        //导联状态
                        case 0x80: {
                            // 更新measurement类型定义，添加leadStatus属性
                            // 更正索引：导联信息在索引1，过载报警在索引2
                            const leadInfo = bytes[1];    // 导联信息字节（正确索引）
                            const overloadInfo = bytes[2]; // 过载报警字节（正确索引）

                            // 解析导联状态（您的逻辑正确，无需修改）
                            const leadStatus = {
                                RA: !!(leadInfo & 0x04),  // BIT2: RA导联脱落信息 (1:脱落)
                                LA: !!(leadInfo & 0x02),  // BIT1: LA导联脱落信息 (1:脱落)
                                LL: !!(leadInfo & 0x01),  // BIT0: LL导联脱落信息 (1:脱落)
                            };
                            // 解析过载状态（您的逻辑正确，无需修改）,false代表正常
                            const overloadStatus = {
                                I: !!(overloadInfo & 0x02),   // BIT1: I导联过载 (1:过载)
                                II: !!(overloadInfo & 0x01),   // BIT0: II导联过载 (1:过载)
                                III: !!(overloadInfo & 0x04),   // BIT2: III导联过载 (1:过载)
                            };
                            // 将导联状态添加到measurement对象中
                            measurement.leadStatus = leadStatus;
                            break;
                        }
                        //测量进度,int bytes[1]
                        case 0x95: {
                            const progress = bytes[1];
                            measurement.value.progress = progress;
                            // 更新静态变量中的进度值，保持进度的连续性
                            this.currentProgress = progress;
                            break;
                        }
                    }
                    break;
                }
                default: {
                    // 不识别的特征UUID，回退到旧解析以尽量兼容
                    return this.parseData(hexString);
                }
            }

            if (Object.keys(measurement.value).length === 0) {
                return null;
            }
            return measurement;
        } catch (error) {
            console.error(error)
            return null;
        }
    }

    // 获取开始命令
    static getStartCommand(): string {
        return this.START_COMMAND;
    }

    // 获取停止命令
    static getStopCommand(): string {
        return this.STOP_COMMAND;
    }

    // 重置所有静态数据，用于新的测量周期
    static resetData(): void {
        this.stValues = [];
        this.currentProgress = null;
    }

    // 滤波处理st值：去除10%最大值，10%最小值，求平均值
    private static filterStValues(values: number[]): number {
        // 创建副本并排序
        const sortedValues = [...values].sort((a, b) => a - b);

        // 计算要移除的元素数量
        const countToRemove = Math.max(1, Math.floor(values.length * 0.1));

        // 移除10%最小值和10%最大值
        const filteredValues = sortedValues.slice(countToRemove, values.length - countToRemove);

        // 计算平均值
        if (filteredValues.length === 0) {
            // 如果过滤后没有值，返回原始数组的平均值
            const sum = values.reduce((acc, val) => acc + val, 0);
            return sum / values.length;
        }

        const sum = filteredValues.reduce((acc, val) => acc + val, 0);
        return Number((sum / filteredValues.length).toFixed(2));
    }
}

export default CardiovascularParser;